package com.gp.shaw.netty.io.im;

import com.gp.shaw.netty.io.im.model.IMMsg;
import com.gp.shaw.netty.io.im.model.IMUser;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.Socket;
import java.util.*;

/**
 * 用户和用户组管理
 * Created by asus on 2018/11/1.
 */
@Getter
@Setter
@Slf4j
public class UserManager {
    private Map<String,IMUser> users = new HashMap<>();

    public IMUser getUser(String id){
        return users.get(id);
    }

    /**
     * 根据用户组ID获取再次用户组下的用户
     * @param groupId
     * @return
     */
    public List<IMUser> getUserByGroup(String groupId){
        Set<String> userIds = users.keySet();
        List<IMUser> targetUsers = new ArrayList<>();
        if(userIds!=null&&userIds.size()>0){
            userIds.stream().forEach(userId->{
                IMUser user = users.get(userId);
                if(user.inThisGroup(groupId)){
                    targetUsers.add(user);
                }
            });
        }
        return targetUsers;
    }

    public synchronized void addUser(IMUser user){
        IMUser imUser = users.get(user.getId());
        if(imUser==null) {
            System.out.println("新用户加入："+user.getId());
        }
        users.put(user.getId(), user);
    }

    public synchronized void removeUser(IMUser user){
        users.remove(user.getId());
        Socket socket = user.getSocket();
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addGroup(String sender, String content) {
        IMUser imUser = users.get(sender);
        if(imUser!=null){
            imUser.addGroup(content);
        }
    }
}
